using AutoMapper;
using Domain.Material_Management;
using Infratructure.Interface;
using MediatR;
using MES.Server.API.Application.Command.Material_Management;
using ReturnValue;
using Yitter.IdGenerator;

namespace MES.Server.API.Application.Handler.Material_Management
{
    public class AddBomHandler : IRequestHandler<AddBomCommand, ApiResult<int>>
    {
        private readonly IRepository<BomModel> bomRepo;
        private readonly IMapper mapper;

        public AddBomHandler(IRepository<BomModel> bomRepo, IMapper mapper)
        {
            this.bomRepo = bomRepo;
            this.mapper = mapper;
        }

        /// <summary>
        /// 添加BOM
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<ApiResult<int>> Handle(AddBomCommand request, CancellationToken cancellationToken)
        {
            var result = new ApiResult<int>();

            // BOM编码不能重复
            var exists = bomRepo.GetAll().Where(a => a.BomCode == request.BomCode && !a.IsDel).FirstOrDefault();
            if (exists != null)
            {
                result.Code = StatusCode.Fail;
                result.Message = "该BOM编码已存在，请重新输入！";
                return await Task.FromResult(result);
            }

            var model = mapper.Map<BomModel>(request);
            model.Id = YitIdHelper.NextId();
            model.CreateTime = DateTime.Now;
            model.IsDel = false;
            
            // 验证必填字段
            if (string.IsNullOrEmpty(model.BomCode))
            {
                result.Code = StatusCode.Fail;
                result.Message = "BOM编码不能为空！";
                return await Task.FromResult(result);
            }
            
            if (string.IsNullOrEmpty(model.BomName))
            {
                result.Code = StatusCode.Fail;
                result.Message = "BOM名称不能为空！";
                return await Task.FromResult(result);
            }
            
            if (model.MaterialGroupId <= 0)
            {
                result.Code = StatusCode.Fail;
                result.Message = "物料群组ID必须大于0！";
                return await Task.FromResult(result);
            }
            
            if (model.ProcessManagementId <= 0)
            {
                result.Code = StatusCode.Fail;
                result.Message = "工序ID必须大于0！";
                return await Task.FromResult(result);
            }

            // 如果有父级BOM，需要验证父级是否存在
            if (request.ParentId.HasValue)
            {
                var parentBom = bomRepo.GetAll().Where(a => a.Id == request.ParentId.Value && !a.IsDel).FirstOrDefault();
                if (parentBom == null)
                {
                    result.Code = StatusCode.Fail;
                    result.Message = "父级BOM不存在！";
                    return await Task.FromResult(result);
                }

                model.Level = parentBom.Level + 1;
                model.ParentId = request.ParentId.Value;

                // 更新父级的IsLeaf状态
                parentBom.IsLeaf = false;
                await bomRepo.UpdateAsync(parentBom);
            }


                var affectedRows = await bomRepo.AddAsync(model);
                
                
                if (affectedRows > 0)
                {
                    result.Code = StatusCode.Success;
                    result.Message = "添加成功！";
                    result.Data = affectedRows;
                }
                else
                {
                    result.Code = StatusCode.Fail;
                    result.Message = "添加失败，数据库操作未成功";
                    result.Data = 0;
                }
            return await Task.FromResult(result);
        }
    }
}
